package com.sneakxy.cloudbase.platform.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import com.sneakxy.cloudbase.platform.bean.FtpConfig;
import com.sneakxy.cloudbase.platform.utils.web.HttpServletResponseUtils;

public class FtpClient {

	private FtpConfig config;
	
	private FTPClient client = new FTPClient();
	
	private boolean login;
	
	public FtpClient(FtpConfig config) {
		this.config = config;
		client.setConnectTimeout(config.getTimeout());
		client.setControlEncoding(config.getEncoding());
	}

	public boolean isLogin() {
		return login;
	}
	
	public boolean login() throws IOException {
		client.connect(config.getIp(), config.getPort());
		client.login(config.getUsername(), config.getPassword());// 登录
        int reply = client.getReplyCode();
		if(!FTPReply.isPositiveCompletion(reply)) {
			client.disconnect();
            return false;
        }
		login = true;
		return true;
	}
	
	public boolean upload(String path, String name, InputStream is) throws IOException {
		if(this.isLogin()) {
			client.setFileType(FTP.BINARY_FILE_TYPE);
			if(!client.changeWorkingDirectory(path)) {
				client.makeDirectory(path);
				client.changeWorkingDirectory(path);
			}
			client.storeFile(name, is);
			is.close();
	        return true;
		}
		return false;
	}
	
	public boolean remove(String path) throws IOException {
		if(this.isLogin()) {
			client.remoteRetrieve(path);
	        return true;
		}
		return false;
	}
	
	@SuppressWarnings("deprecation")
	public boolean download(String path, OutputStream out) throws IOException {
		boolean result = true;
		if(this.isLogin()) {
			client.enterLocalPassiveMode();
			result = client.retrieveFile(path, out);
			IOUtils.closeQuietly(out);
		}
		return result;
	}
	
	public void download(HttpServletRequest request, HttpServletResponse response, String path, long fileLength) throws IOException {
		if(this.isLogin()) {
			client.enterLocalPassiveMode();
			HttpServletResponseUtils.download(request, response, client.retrieveFileStream(path), fileLength);
		}
	}
	
	public void close() {
		if (client != null && client.isConnected()) {
            try {
            	client.logout();
            } catch (IOException e) {
            	// 不抛出异常
            } finally {
            	try {
					client.disconnect();
				} catch (IOException e) {
					// 不抛出异常
				}
            }
        }
		login = false;
	}

}
